package cn.yili12.server.websocket.handler;

import cn.yili12.server.websocket.RequestUriUtils;
import cn.yili12.server.websocket.WebSocketProperties;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@ChannelHandler.Sharable
@Component
public class NioWebSocketParamHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    @Autowired
    private WebSocketProperties webSocketProperties;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("数据类型：{}", msg.getClass());
        if (msg instanceof FullHttpRequest) {
            fullHttpRequestHandler(ctx, (FullHttpRequest) msg);
        }
        super.channelRead(ctx, msg);
    }

    /**
     * 处理连接请求，客户端WebSocket发送握手包时会执行这一次请求
     *
     * @param ctx
     * @param request
     */
    private void fullHttpRequestHandler(ChannelHandlerContext ctx, FullHttpRequest request) {
        String uri = request.uri();
        log.info("接收到客户端的握手包：{}", ctx.channel().id());
        Map<String, String> params = RequestUriUtils.getParams(uri);
        log.info("客户端请求参数：{}", params);
        if (uri.startsWith(webSocketProperties.getPath()))
            request.setUri(webSocketProperties.getPath());
        else
            ctx.close();
    }

}